<script>
  let data = [
    {
      id: 1,
      pid: 0,
      name: "总公司2",
    },
    {
      id: 2,
      pid: 1,
      name: "北京分公司",
    },
    {
      id: 3,
      pid: 1,
      name: "上海分公司",
    },
    {
      id: 4,
      pid: 2,
      name: "大兴办事处",
    },
    {
      id: 5,
      pid: 2,
      name: "海淀办事处",
    },
    {
      id: 6,
      pid: 3,
      name: "宝山办事处",
    },
    {
      id: 7,
      pid: 3,
      name: "虹口足球场",
    },
  ];
  function transListToTreeData(data, rootValue) {
    const arr = [];
    data.forEach((item) => {
      if (item.pid === rootValue) {
        arr.push(item);
        const children = transListToTreeData(data, item.id);
        children.length && (item.children = children);
      }
    });
    return arr;
  }
  function treeForeach (tree, func) {  
    let node, list = [...tree]
    while (node = list.shift()) {    
      func(node)    
      node.children && list.push(...node.children)  
    }
  }
  
  console.log('aa', transListToTreeData(data, 0))
  
</script>
